package com.hc.comm.utils;

import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @author
 * @ClassName: SecurityCode
 * @date 2014-8-17 上午9:59:14
 */
public class SecurityUtils {

    private static final Charset charset = Charset.forName("UTF-8");

    private static final String BASE_CHECK_CODE = "0123456789abcdefghijklnmopqrstuvwxyz";

    /**
     * 加密
     *
     * @param content  需要加密的内容
     * @param password 加密密码
     * @return
     */
    public static byte[] encrypt(String content, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(password.getBytes(charset)));
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");// 创建密码器
            byte[] byteContent = content.getBytes(charset);
            cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(byteContent);
            return result; // 加密
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     *
     * @param content  待解密内容
     * @param password 解密密钥
     * @return
     */
    public static byte[] decrypt(byte[] content, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(password.getBytes(charset)));
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(content);
            return result; // 加密
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param length
     * @return String
     * @Title: getRandomNumber
     * @Description: 获取数字验证码
     */
    public static String getRandomNumber(int length) {
        if (length <= 0) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            sb.append((int) Math.floor(Math.random() * 9 + 1));
        }
        return sb.reverse().toString();
    }

    /**
     * 根据基数来生成随机码
     *
     * @param base
     * @param length
     * @return String
     */
    public static String getRandomNumber(String base, int length) {
        if (length <= 0) {
            return base;
        }
        length = length - base.length();

        StringBuffer sb = new StringBuffer(base);
        for (int i = 0; i < length; i++) {
            sb.append((int) Math.floor(Math.random() * 10));
        }
        return sb.reverse().toString();
    }

    /**
     * @param length 生成字符串的长度
     * @return String
     * @Title: getRandomCode
     * @Description: 获取随机数字符串
     */
    public static String getRandomCode(int length) {
        if (length <= 0) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            sb.append(BASE_CHECK_CODE.charAt((int) Math
                    .floor(Math.random() * BASE_CHECK_CODE.length())));
        }
        return sb.reverse().toString().toUpperCase();
    }

    /**
     * md5
     *
     * @param content
     * @return String
     * @date 2015年12月25日 下午5:14:10
     */
    public static String md5(String content) {
        return DigestUtils.md5Hex(content).toUpperCase();
    }

    /**
     * SHA1 加密
     *
     * @param str
     * @return
     */
    public static String SHA1(String str) {
        try {
            MessageDigest digest = java.security.MessageDigest
                    .getInstance("SHA-1"); //如果是SHA加密只需要将"SHA-1"改成"SHA"即可
            digest.update(str.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexStr = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexStr.append(0);
                }
                hexStr.append(shaHex);
            }
            return hexStr.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}
